<?php
function log_post_update_entry( $form, $entry_id, $original_entry ) {
	$user_level = wp_get_current_user()->user_level;
	if ( intval( $user_level ) > 6 ) {
		return;
	}
	$entry = GFAPI::get_entry( $entry_id );
	GFAPI::update_entry( $original_entry, $entry_id );
}

/**
 * return GF_Field_HTML
 *
 * @param $form :array
 * @param $id :int
 */
function getFieldById( $form, $id
) {
	/** @var GF_Field_HTML[] $fields */
	$fields = $form['fields'];
	foreach ( $fields as $field ) {
		if ( $field['id'] === $id ) {
			return $field;
		}
	}

	return null;

}

function add_sidebar_text_before( $form, $entry ) {
	include( tiremanager_plugin_dir_path . 'formsconfig.php' );
	$userLevel = intval( wp_get_current_user()->user_level );
	/** @var array $delivered_fields comes from formconfig.php */
	foreach ( $delivered_fields as $delivered_field => $delivered_value ) {
		$GF_field_HTML   = getFieldById( $form, intval( $delivered_field ) )['label'];
		$delivery_status = $entry[ $delivered_field ];
		$btn_class       = strtolower( $delivery_status ) == 'yes' ? 'button button-primary' : 'button button-secondary';
		echo "
<script>
function changeEntityDeliveryStatus(currStatus) {
  const setStatus = currStatus.toString().toLowerCase() === 'yes' ? 'no' : 'yes';
  const data =    {
      field: '$delivered_field',
      entry_id: '${entry['id']}',
      status:setStatus,
      date:Math.round(new Date().getTime()/1000)
      };
  fetch(ajaxurl,{
      method:\"POST\",
      headers:{
        \"Content-Type\": \"application/x-www-form-urlencoded\",
        },
      body:\"action=tire_manager_change_delivery_status&data=\"+JSON.stringify(data),
  }    ).finally(()=>window.location.reload())
  
  
    
  }
  function gform_edit_button_disable() {
      jQuery(
          function() {
                        jQuery('#gform_edit_button').attr('disabled',true).hide();
      })
  }
</script>";
		if ( strtolower( $delivery_status ) == 'no' || $userLevel > 7) {
			echo "

<div class='stuffbox'><h3><span class='hndle'>تغییر $GF_field_HTML</span></h3><div class='inside'>
            <button style='margin: 1em' type=\"button\" class=\"$btn_class \" onclick='changeEntityDeliveryStatus(\"$delivery_status\")'>
            تغییر $GF_field_HTML 
</button>
            <br/></div></div>";
		}
		if ( $userLevel < 9 ) {
			echo '
		    <script>
		    gform_edit_button_disable();
</script>
		    ';
		}

	}

}

function changeEntityDeliveryStatus() {
	$data1                           = stripslashes( $_REQUEST['data'] );
	$data                            = json_decode( $data1 );
	$entry_id                        = intval( $data->entry_id );
	$entry                           = GFAPI::get_entry( $entry_id );
	$entry[ intval( $data->field ) ] = $data->status;
	if(!isset($delivered_date_fields)){
		include( tiremanager_plugin_dir_path . 'formsconfig.php' );
	}
	/** @var array $delivered_date_fields  defined in formsconfig.php*/
	foreach ($delivered_date_fields as $delivered_date_field=>$value){
		$entry[intval($delivered_date_field)]=jdate('Y-m-d',time(),false,false,'en');
	}
	GFAPI::update_entry( $entry, $entry_id );

	return 1;
}

add_action( 'wp_ajax_tire_manager_change_delivery_status', 'changeEntityDeliveryStatus' );
add_action( 'gform_after_update_entry_' . $tire_gravity_form_id, 'log_post_update_entry', 10, 3 );
add_action( 'gform_entry_detail_sidebar_before', 'add_sidebar_text_before', 10, 2 );

//Edit entry view page
/**
 *
 *
 * add_action( 'gform_entry_detail_sidebar_middle', 'add_sidebar_text_middle', 10, 2 );
 * function add_sidebar_text_middle( $form, $entry ) {
 * echo "<div class='stuffbox'><h3><span class='hndle'>Stuff in the Middle</span></h3><div class='inside'>text added in the middle!<br/></div></div>";
 * }
 *
 *
 * add_action( 'gform_entry_detail_sidebar_after', 'add_sidebar_text_after', 10, 2 );
 * function add_sidebar_text_after( $form, $entry ) {
 * echo "<br/><div class='stuffbox'><h3><span class='hndle'>More Cool Stuff</span></h3><div class='inside'>text added after!<br/></div></div>";
 * }
 **/
